using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Write.Application.Command;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure.BaseRepository;
using System;

namespace S.M.SmartMedical.API.Write.Application.Handler
{
    /// <summary>
    /// 批量删除医院命令处理程序
    /// 处理医院批量删除逻辑
    /// </summary>
    public class BatchDeleteHospitalsHandler : IRequestHandler<BatchDeleteHospitalsCommand, APIResult<bool>>
    {
        private readonly IRepository<Hospital> _hospitalRepository;
        private readonly ILogger<BatchDeleteHospitalsHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public BatchDeleteHospitalsHandler(
            IRepository<Hospital> hospitalRepository,
            ILogger<BatchDeleteHospitalsHandler> logger)
        {
            _hospitalRepository = hospitalRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理批量删除医院请求
        /// </summary>
        public async Task<APIResult<bool>> Handle(BatchDeleteHospitalsCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始批量删除医院，IDs：{@Ids}", request.Ids);

                if (request.Ids == null || !request.Ids.Any())
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "请选择要删除的医院"
                    };
                }

                // 查询所有待删除的医院
                var hospitals = _hospitalRepository.GetQueryable()
                    .Where(h => request.Ids.Contains(h.Id) && !h.IsDeleted)
                    .ToList();

                if (!hospitals.Any())
                {
                    _logger.LogWarning("未找到要删除的医院");
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "未找到要删除的医院"
                    };
                }

                // 批量更新删除标记
                foreach (var hospital in hospitals)
                {
                    hospital.IsDeleted = true;
                    hospital.UpdateTime = DateTime.Now;
                }

                // 由于仓储没有UpdateRangeAsync，我们逐个更新
                int updatedCount = 0;
                foreach (var hospital in hospitals)
                {
                    updatedCount += await _hospitalRepository.UpdateAsync(hospital);
                }
                if (updatedCount <= 0)
                {
                    _logger.LogError("批量删除医院失败，数据库操作失败");
                    return new APIResult<bool>
                    {
                        Code = APIEnum.Fail,
                        Message = "批量删除医院失败"
                    };
                }

                _logger.LogInformation("批量删除医院成功，共删除 {Count} 条记录", updatedCount);

                return new APIResult<bool>
                {
                    Code = APIEnum.OK,
                    Message = "批量删除成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除医院时发生错误");
                return new APIResult<bool>
                {
                    Code = APIEnum.Fail,
                    Message = "批量删除失败：" + ex.Message
                };
            }
        }
    }
}